package com.fang.transfer.file.listener;

import com.fang.transfer.file.ThreadContext;
import com.fang.transfer.file.common.*;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.code.ServiceSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;
import com.fang.transfer.file.service.FileSendRequestService;
import com.fang.transfer.file.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.DatagramPacket;
import java.net.InetAddress;

/**
 * 更新udp地址
 */
@Service
@Slf4j
public class UDPAddrUpdateListener extends RequestListener<TransferFileRequest> {


    @Autowired
    private FileSendRequestService fileSendRequestService;

    @Autowired
    private NettyHandle nettyHandle;

    @Override
    public void handle(TransferFileRequest param) {
        TransferFileRequest request = fileSendRequestService.getById(param.getId());
        String role = param.getRole();
        User curUser = "1".endsWith(role) ? request.getSendUser() : request.getReceiveUser();
        DatagramPacket packet = ThreadContext.getUdpPacketThreadLocal();
        InetAddress address = packet.getAddress();
        String hostAddress = address.getHostAddress();
        int port = packet.getPort();
        log.info("更新UPD地址 请求id:{} 角色:{} host:{}  port:{}", request.getId(), role, hostAddress, port);
        curUser.setHost(hostAddress);
        curUser.setPort(port);

        User sendUser = request.getSendUser();
        User receiveUser = request.getReceiveUser();
        if (StringUtils.hasLength(sendUser.getHost()) && StringUtils.hasLength(receiveUser.getHost())) {
            nettyHandle.send(sendUser.getId(), ServiceSendCode.UDP_ADDR_TO_CLIENT, request);
            nettyHandle.send(receiveUser.getId(), ServiceSendCode.UDP_ADDR_TO_CLIENT, request);
        }
    }

    @Override
    public String getCode() {
        return ClientSendCode.UPD_ADDR_UPDATE;
    }

}
